package com.xinou.daily_report.expand.sso.mini;

import com.xinou.common.base.exception.BusException;
import com.xinou.common.util.SpringContextBeanUtil;
import com.xinou.sso.config.shiro.jwt.JwtToken;
import com.xinou.sso.dto.UserDTO;
import com.xinou.sso.enumerate.HttpSsoStatusEnum;
import com.xinou.sso.mapper.SysUserMapper;
import com.xinou.sso.util.ShiroUtil;
import org.apache.shiro.ShiroException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

/**
 * @author lizhongyuan
 */
public class MiniRealm extends AuthorizingRealm {

    @Override
    public String getName() {
        return "miniRealm";
    }

    @Override
    protected Object getAuthorizationCacheKey(PrincipalCollection principals) {
        return ((UserDTO) principals.getPrimaryPrincipal()).getUserId();
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof MiniToken;
    }

    /**
     * 权限认证
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return ShiroUtil.getSimpleAuthorizationInfo();
    }

    /**
     * 登录认证;
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        MiniToken miniToken = (MiniToken) authenticationToken;
        try {
            Long userId = miniToken.getUserId();
            //查出是否有此用户
            UserDTO dto = SpringContextBeanUtil.getBean(SysUserMapper.class).getUserByUserId(userId);
            if (dto == null) {
                throw new  BusException(HttpSsoStatusEnum.RE_CODE_NO_HAVE_ACCOUNT);
            }
            return new SimpleAuthenticationInfo(dto, userId, getName());
        } catch (BusException e) {
            throw e;
        } catch (Exception e){
            throw new ShiroException("shiro exception");
        }
    }

    public void clearAuthorizationInfo() {
        clearAuthorizationInfo(ShiroUtil.getUserId());
    }

    public void clearAuthenticationInfo() {
        clearAuthenticationInfo(ShiroUtil.getUserId());
    }

    public void clearAuthorizationInfo(Long userId) {
        getAuthorizationCache().remove(userId);
    }

    public void clearAuthenticationInfo(Long userId) {
        getAuthenticationCache().remove(userId);
    }

    public void clearAuthorizationAll() {
        if (getAuthorizationCache() == null) {
            return;
        }
        getAuthorizationCache().clear();
    }

    public void clearAuthenticationAll() {
        if (getAuthenticationCache() == null) {
            return;
        }
        getAuthenticationCache().clear();
    }

}
